<template>
  <div v-for="followVO in followVOList"
       style="display: flex; align-items: center; justify-content: space-between; height: 56px">
    <div style="display: flex; align-items: center; justify-content: center; margin-left: 12px">
      <van-image
          round
          width="3rem"
          height="3rem"
          :src="followVO.avatarUrl"
          style="margin-top: 20px; margin-bottom: 20px; box-shadow: 0 0 15px rgba(0, 0, 0, 0.4)"
          @click="toPersonalPage(followVO.id)"
      />
      <span style="margin-left: 12px; color: #999999">{{ followVO.username }}</span>
    </div>
    <van-button v-if="!followVO.isFollowed" type="primary" style="margin-right: 20px"
                @click="addFollow(followVO.id, followVO.isFollowed)">关注
    </van-button>
    <van-button v-else type="success" style="margin-right: 20px"
                @click="deleteFollow(followVO.id, followVO.isFollowed)">取关
    </van-button>
  </div>
  <van-divider/>

</template>

<script setup lang="ts">

import {FollowVOType} from "../models/followVO";
import {defineEmits} from "vue";
import myAxios from "../plugins/myAxios.ts";
import {showToast} from "vant";
import {useRouter} from "vue-router";

interface FollowCardList {
  followVOList: FollowVOType[];
}

withDefaults(defineProps<FollowCardList>(), {
  loading: true,
});

const router = useRouter();

const emit = defineEmits<{
  (event: 'update-followed', userId: number): void
}>();

const addFollow = async (id, followed) => {
  const res: any = await myAxios.post('/follow/add', {
    userId: id,
    isFollowed: followed,
  });
  if (res?.code === 0) {
    emit('update-followed', !followed);
  } else {
    showToast('关注失败' + (res.description ? `，${res.description}` : ''));
  }
};

const deleteFollow = async (id, followed) => {
  const res: any = await myAxios.post('/follow/delete', {
    userId: id,
    isFollowed: followed,
  });
  if (res?.code === 0) {
    emit('update-followed', id); // 改为传递用户ID
    showToast('取关成功');
  } else {
    showToast('取关失败' + (res.description ? `，${res.description}` : ''));
  }
};

const toPersonalPage = (id) => {
  router.push(`/user/${String(id)}`);
};
</script>

<style scoped>

</style>